package com.ylc.proxy5;

import com.ylc.proxy5.AOP.AOP;
import com.ylc.proxy5.Service.Service;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author: ylc
 * @Description:
 * @Date Created in 2022-07-18 15:18
 */
public class ProxyFactory {
    //通过方法参数传入目标对象和切面对象
    public static Object getAgent(Service target, AOP aop) {

        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object obj = null;
                        try {
                            aop.before();  //灵活的进行切面功能切换
                            obj = method.invoke(target, args);  //灵活的进行业务功能切换
                            aop.after();  //灵活的进行切面功能切换
                        } catch (Exception e) {
                            aop.exception();  //灵活的进行切面功能切换
                        }
                        return obj;//目标方法的返回值
                    }
                }); //返回动态代理对象
    }
}
